# -*- coding: utf-8 -*-
#
# Copyright (c) 2012, Rafael Pivato
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Rafael Pivato nor the names of its contributors
#       may be used to endorse or promote products derived from this
#       software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL RAFAEL PIVATO BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import webapp2
from wowgae.web import WebHandler
from wowgae.model import WikiPage
from wowgae.model import Character
from wowgae.model import CharacterActivation
from wowgae.decorators import membership_required
from wowgae.model.account import Account
from wowgae.icon import WowIconLoader
from wowgae import human_delta_now


class ReportsHandler(WebHandler):
    """Shows available reports to the user."""

    def __public_data(self):
        data = [
            {'href': webapp2.uri_for('reports-latest_pages'),
             'title': u'Últimas Páginas'},
            {'href': webapp2.uri_for('reports-latest_accounts'),
             'title': u'Últimas Contas'},
            {'href': webapp2.uri_for('reports-missing_activation'),
             'title': u'Faltando Ativação'},
            {'href': webapp2.uri_for('reports-pending_activation'),
             'title': u'Ativação Pendente'},
            {'href': webapp2.uri_for('reports-lows_missing_activation'),
             'title': u'Níveis Baixo Faltando Ativação'},
        ]
        return data

    @membership_required
    def get(self):
        """Returns the index for reports."""
        self.template.use('report', 'list')
        public_data = self.__public_data()
        data = {'public': public_data}
        self.template.update(report=data)
        self.template.write()


class LatestPagesHandler(WebHandler):
    """Shows the latest modified pages to the user."""

    def __fetch_data(self):
        """Load report data."""
        data = []
        entities = WikiPage.latest_modifications()
        for entity in entities:
            href = webapp2.uri_for('wiki', self.request, page=entity.name())
            title = entity.title
            author = entity.author
            delta_value, delta_label = human_delta_now(entity.modified)
            delta = {'value': delta_value, 'label': delta_label}
            revision = entity.revision
            data.append({'href': href, 'title': title, 'author': author,
                         'delta': delta, 'revision': revision})
        return data

    @membership_required
    def get(self):
        """Shows a list of latest modified pages to the user."""
        self.template.use('report', 'latest_pages')
        results_data = self.__fetch_data()
        data = {'results': results_data}
        self.template.update(report=data)
        self.template.write()


class LatestAccountsHandler(WebHandler):
    """Shows the latest created accounts activated."""

    def __fetch_data(self):
        """Load report data."""
        data = []
        entities = Account.latest_created()
        for entity in entities:
            name = entity.name
            delta_value, delta_label = human_delta_now(entity.created)
            delta = {'value': delta_value, 'label': delta_label}
            data.append({'name': name, 'delta': delta})
        return data

    @membership_required
    def get(self):
        """Shows a list of latest accounts created."""
        self.template.use('report', 'latest_accounts')
        results_data = self.__fetch_data()
        data = {'results': results_data}
        self.template.update(report=data)
        self.template.write()


class MissingActivationHandler(WebHandler):
    """Shows characters missing activation."""

    def __fetch_data(self):
        """Load report data."""
        data = []
        entities = Character.missing_activation()
        entities = sorted(entities, key=lambda e: e.name)
        thumb_url = 'http://us.battle.net/static-render/us/%s'
        for character in entities:
            data.append({
                'name': character.name,
                'level': character.level,
                'thumbnail': thumb_url % (character.thumbnail),
                'race': {'icon': WowIconLoader.race_icon(character.race,
                                                         character.gender)},
                'klass': {'icon': WowIconLoader.klass_icon(character.klass)},
            })
        return data

    @membership_required
    def get(self):
        """Shows a list of characters missing activation."""
        self.template.use('report', 'missing_activation')
        results_data = self.__fetch_data()
        data = {'results': results_data}
        self.template.update(report=data)
        self.template.write()


class PendingActivationHandler(WebHandler):
    """Shows characters pending activation."""

    def __fetch_data(self):
        """Load report data."""
        data = []
        entities = CharacterActivation.old_activations()
        entities = sorted(entities, key=lambda e: e.name)
        thumb_url = 'http://us.battle.net/static-render/us/%s'
        for entity in entities:
            character = entity.character()
            data.append({
                'name': character.name,
                'level': character.level,
                'thumbnail': thumb_url % (character.thumbnail),
                'race': {'icon': WowIconLoader.race_icon(character.race,
                                                         character.gender)},
                'klass': {'icon': WowIconLoader.klass_icon(character.klass)},
            })
        return data

    @membership_required
    def get(self):
        """Shows a list of characters with pending activations."""
        self.template.use('report', 'pending_activation')
        results_data = self.__fetch_data()
        data = {'results': results_data}
        self.template.update(report=data)
        self.template.write()


class LowsMissingActivationHandler(WebHandler):
    """Shows low level characters missing activation."""

    def __fetch_data(self):
        """Load report data."""
        data = []
        entities = Character.run_low_level_missing_activation()
        thumb_url = 'http://us.battle.net/static-render/us/%s'
        count = 0
        for character in entities:
            data.append({
                'name': character.name,
                'level': character.level,
                'thumbnail': thumb_url % (character.thumbnail),
                'race': {'icon': WowIconLoader.race_icon(character.race,
                                                         character.gender)},
                'klass': {'icon': WowIconLoader.klass_icon(character.klass)},
            })
            count = count + 1
            if count == 50:
                break
        return data

    @membership_required
    def get(self):
        """Shows a list of characters missing activation."""
        self.template.use('report', 'lows_missing_activation')
        results_data = self.__fetch_data()
        data = {'results': results_data}
        self.template.update(report=data)
        self.template.write()
